package world2d;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

import utils.Acessory;
import utils.Door;
import utils.Room;
import utils.World;
import utils.string_parse.StringParse;
import aw.Agent;
import aw.AlienWorldImpl;



public class World2d extends JPanel implements ActionListener, Serializable {
	
	private static final long serialVersionUID = 227L;
	
	private static final int POSITION_DIM = 25;
	private static final int DIVIDE_DIM = 2;
	private static final int DIVIDE_DIM2 = 1;
	private static final String doorClosed = "closed";
	private static final String doorLocked = "locked";
	
    World _world;
    Image star;
    Timer timer;
    int _gameWidth, _gameHeight;
    int x, y;

    public World2d(World world, int gameWidth, int gameHeight) {
    	
    	_world = world;
    	_gameWidth = gameWidth;
    	_gameHeight = gameHeight;
    	
        setBackground(Color.decode("#DDDDDD"));
        
        setSize(new Dimension(1200, 1200));
        
        setDoubleBuffered(true);
        
        timer = new Timer(25, this);
        timer.start();
        
        
    }
    
    public void DrawRoom(Graphics2D g2d, Room room){
    	int initX = room.getFirstPosX();
    	int initY = room.getFirstPosY();
    	int lastX = room.getLastPosX();
    	int lastY = room.getLastPosY();
    	
    	for(int i=initX;i<=lastX;i++){
        	for(int j=initY;j<=lastY;j++){
        		int realInitX = i*(POSITION_DIM)+(DIVIDE_DIM2);
        		int realInitY = Math.abs(j*(POSITION_DIM)-(_gameHeight-(DIVIDE_DIM2)));
        		BasicStroke cenaryBodes = new BasicStroke(DIVIDE_DIM);
            	g2d.setColor(new Color(240,240,240));
            	g2d.setStroke(cenaryBodes);
            	g2d.fillRect(realInitX, realInitY-POSITION_DIM, POSITION_DIM-DIVIDE_DIM, POSITION_DIM-DIVIDE_DIM);
            	if(j==lastY){
            		g2d.setColor(new Color(0,0,0));
            		ArrayList<Door> doors = room.getDoors();
            		for (Door door : doors) {
            			String[] pos;
            			if(door.get_room1() == room.getId())
            				pos = door.get_pos1().split("[*]");
            			else pos = door.get_pos2().split("[*]");
            			int posX = Integer.parseInt(pos[0]);
            			int posY = Integer.parseInt(pos[1]);
						if(posX ==(i-initX) && posY ==(j-initY)){
							String state = door.get_state();
							if(state.equals(doorClosed)) g2d.setColor(Color.YELLOW);
							else if (state.equals(doorLocked)) g2d.setColor(Color.RED);
							else g2d.setColor(Color.GREEN);
						}
					}
            	}
            	else g2d.setColor(new Color(255,255,255));
            	g2d.drawLine(realInitX+(DIVIDE_DIM2), realInitY-POSITION_DIM-DIVIDE_DIM2, realInitX+POSITION_DIM-DIVIDE_DIM, realInitY-POSITION_DIM-DIVIDE_DIM2);
            	if(i==lastX){
            		g2d.setColor(new Color(0,0,0));
            		ArrayList<Door> doors = room.getDoors();
            		for (Door door : doors) {
            			String[] pos;
            			if(door.get_room1() == room.getId())
            				pos = door.get_pos1().split("[*]");
            			else pos = door.get_pos2().split("[*]");
            			int posX = Integer.parseInt(pos[0]);
            			int posY = Integer.parseInt(pos[1]);
						if(posX ==(i-initX) && posY ==(j-initY)){
							String state = door.get_state();
							if(state.equals(doorClosed)) g2d.setColor(Color.YELLOW);
							else if (state.equals(doorLocked)) g2d.setColor(Color.RED);
							else g2d.setColor(Color.GREEN);
						}
					}
            		
            	}
            	else g2d.setColor(new Color(255,255,255));
            	g2d.drawLine(realInitX+POSITION_DIM-(DIVIDE_DIM2), realInitY-DIVIDE_DIM-DIVIDE_DIM2, realInitX+POSITION_DIM-(DIVIDE_DIM2), realInitY-POSITION_DIM-DIVIDE_DIM2);
            }
    	}
    	
    	DrawAcessories(g2d,room,initX,initY);
    	DrawAgents(g2d,room,initX,initY);
    	
    	
    }
    
    public void DrawAcessories(Graphics2D g2d, Room room, int initX, int initY){
    	ArrayList<Acessory> acessories = room.getAcessories();
    	
    	for (Acessory acessory : acessories) {
			String id = acessory.getId();
			int xPos = acessory.getPosX();
			int yPos = acessory.getPosY();
			ImageIcon ii = new ImageIcon("res/"+id+".png");
		    Image acessoryImage= ii.getImage();
		    
		    int realInitX = (initX+xPos)*(POSITION_DIM)+(DIVIDE_DIM2);
    		int realInitY = Math.abs((initY+yPos)*(POSITION_DIM)-(_gameHeight-(DIVIDE_DIM2)))-POSITION_DIM;
		    g2d.drawImage(acessoryImage, realInitX, realInitY, this);
		}
    }
    
    public void DrawAgents(Graphics2D g2d,Room room, int initX, int initY){
    	
    	
    	ArrayList<Agent> agents = AlienWorldImpl.agents;
    	
    	for (Agent agent : agents) {
			String id = agent.get_id().split(":")[2];
			int roomId = room.getId();
			int agentRoomId = agent.get_roomID();
			if(roomId==agentRoomId){
				String[] pos = StringParse.coordinatesParse(agent.getPosition());
				int xPos = Integer.parseInt(pos[0]);
				int yPos = Integer.parseInt(pos[1]);
				ImageIcon ii = null;
				
				if(agent.get_team()==1)	ii = new ImageIcon("res/androidTeam1.png");
				else ii = new ImageIcon("res/androidTeam2.png");
				
			    Image agentImage= ii.getImage();
			    
			    int realInitX = (initX+xPos)*(POSITION_DIM)+(DIVIDE_DIM2);
	    		int realInitY = Math.abs((initY+yPos)*(POSITION_DIM)-(_gameHeight-(DIVIDE_DIM2)))-POSITION_DIM;
			    g2d.drawImage(agentImage, realInitX, realInitY, this);
			    g2d.drawString(id, realInitX+15, realInitY+15);
			}
		}
    }
    
    public void DrawAgentsInformations(Graphics2D g2d/*,Room room, int initX, int initY*/){
    	
    	
    	ArrayList<Agent> agents = AlienWorldImpl.allAgents;
    	
    	
    	
    	for (Agent ag : agents) {
    		String id = ag.get_id().split(":")[2];
        	int team = ag.get_team();
        	int roomAg = ag.get_roomID();
        	String[] status = ag.get_agentState().split("[*]");
        	String gold = status[0];
        	String life = status[1];
        	ArrayList<String> ob = ag.get_agentCollection();
        	String obAg="";

        	int posY = 10+((team-1)*130);
        	int posX = _gameWidth+10+((Integer.parseInt(id)-1)*110);
            
            if(team==1) g2d.setColor(new Color(230,0,0));
            else g2d.setColor(new Color(0,100,0));
        
            //g2d.fillRect(posX, posY-10, 120, 130);

        	String colorTeam;
        	if(team==1) colorTeam="red";
        	else colorTeam="green";
        	
        	g2d.drawString("Agent: "+id, posX, posY+15);
        	g2d.drawString("Team: "+colorTeam, posX, posY+30);
        	g2d.drawString("Actual Room: "+roomAg, posX, posY+45);
        	g2d.drawString("Gold: "+gold, posX, posY+60);
        	g2d.drawString("Life: "+life, posX, posY+75);
        	
        	
        	int objToPrint = 0;
        	int lineToprint = 1;
        	for(String object: ob){
        		objToPrint++;
        		obAg += object+" ";
        		if(lineToprint == 1 && objToPrint == 4){
        			g2d.drawString("Objects: "+obAg, posX, posY+75+(15*lineToprint));
        			objToPrint = 0;
        			lineToprint++;
        			obAg="";
        		}else if(lineToprint > 1 && objToPrint == 8){
        			g2d.drawString(obAg, posX, posY+75+(15*lineToprint));
        			objToPrint = 0;
        			lineToprint++;
        			obAg="";
        		}
        	}
        	
        	if(lineToprint == 1) g2d.drawString("Objects: "+obAg, posX, posY+75+(15*lineToprint));
        	else if(!obAg.equals("")) g2d.drawString(obAg, posX, posY+75+(15*lineToprint));
        	
		}
    }
    
    
    private void DrawFinalGame(Graphics2D g2d) {
		// TODO Auto-generated method stub
    	if(AlienWorldImpl.finalWinner==0) return;
    	
    	int teamWinner = AlienWorldImpl.finalWinner;
        String winner;
        if(teamWinner==1) winner="RED";
        else winner="GREEN";
    	int goldT1 = AlienWorldImpl.finalGoldT1;
    	int goldT2 = AlienWorldImpl.finalGoldT2;
    	BasicStroke cenaryBodes = new BasicStroke(DIVIDE_DIM);
    	g2d.setColor(new Color(200,200,200));
    	g2d.setStroke(cenaryBodes);
    	
    	g2d.fillRect((int) (_gameWidth*.15), 100, (int) (_gameWidth*0.7), 200);
    	g2d.setColor(new Color(0,0,0));
    	g2d.setFont(new Font("Orena", Font.PLAIN, 24));
    	if(teamWinner==0) g2d.drawString("DRAW", _gameWidth/2-30, _gameHeight/2-50);
    	else g2d.drawString("THE WINNER IS TEAM " + winner, _gameWidth/2-180, _gameHeight/2-130);
    	g2d.drawString("RED - " + goldT1 + " Gold  VS  GREEN - " + goldT2 + " Gold", _gameWidth/2-220, _gameHeight/2-100);
    	
    	
    	
	}
    

    public void paint(Graphics g) {
    	try{
	        super.paint(g);
	
	        Graphics2D g2d = (Graphics2D) g;
	        
	        BasicStroke cenaryBodes = new BasicStroke(DIVIDE_DIM);
	        g2d.setStroke(cenaryBodes);
	        g2d.drawLine(0, 0, (_world.getXmax()+1)*(POSITION_DIM), 0);
	        g2d.drawLine(0, 0, 0, (_world.getYmax()+1)*(POSITION_DIM));
	        g2d.drawLine((_world.getXmax()+1)*(POSITION_DIM), 0, (_world.getXmax()+1)*(POSITION_DIM), (_world.getYmax()+1)*(POSITION_DIM));
	        g2d.drawLine(0, (_world.getYmax()+1)*(POSITION_DIM), (_world.getXmax()+1)*(POSITION_DIM), (_world.getYmax()+1)*(POSITION_DIM));
	        
	        for(int i = 0; i<_world.getNumberofRooms(); i++){
	        	Room room = _world.getRoom(i);
	        	DrawRoom(g2d, room);
	        }
	        
	        DrawAgentsInformations(g2d);
	        
	        DrawFinalGame(g2d);
	        
	        Toolkit.getDefaultToolkit().sync();
	        g.dispose();
	
		}catch(Exception e1){
			//System.out.println("excecao");
		}
    }
    
    
	public void actionPerformed(ActionEvent e) {
    	repaint(); 
    }
}